package com.kwok.openplatform.common.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Util {

    // 指定加密算法MD5的KEY
    private static final String MD5_KEY = "MD5";

    // 全局数组
    private static final String[] strDigits = { "0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

    // 返回形式为数字跟字符串
    private static String byteArrayToString(byte b) {
        int iR = b;
        if (iR < 0) {
            iR += 256;
        }
        int iD1 = iR / 16;
        int iD2 = iR % 16;
        return strDigits[iD1] + strDigits[iD2];
    }

    // 转换字节数组为16进制字符串
    private static String byteToString(byte[] b) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            sb.append(byteArrayToString(b[i]));
        }
        return sb.toString();
    }

    /**
     * MD5加密一次
     * @param password
     * @return
     * @throws RuntimeException
     */
    public static String encrypt(String password){
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance(MD5_KEY);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        // md.digest() 该函数返回值为存放哈希值结果的byte数组
        return byteToString(md.digest(password.getBytes()));
    }

    /**
     * MD5加盐加密
     * @param password
     * @param salt
     * @return
     * @throws RuntimeException
     */
    public static String encryptWithSalt(String password, String salt) {
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance(MD5_KEY);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        // md.digest() 该函数返回值为存放哈希值结果的byte数组
        return byteToString(md.digest((password+salt).getBytes()));
    }

    // MD5加密三次
    public static String encryptThreeTimes(String password) {
        String md5Str1 = encrypt(password);
        String md5Str2 = encrypt(md5Str1);
        String md5Str3 = encrypt(md5Str2);
        return md5Str3;
    }

}